package com.youlai.boot.shared.websocket.listener;

import com.youlai.boot.shared.websocket.model.ChatMessage;
import com.youlai.boot.shared.websocket.service.OnlineUserService;
import com.youlai.boot.system.event.UserConnectionEvent;
import com.youlai.boot.system.model.vo.LpsOrderNODownloadVO;
import com.youlai.boot.system.service.LpsOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * 在线用户监听器
 *
 * @author haoxr
 * @since 2024/9/25
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OnlineUserListener {

    private final SimpMessagingTemplate messagingTemplate;
    private final OnlineUserService onlineUserService;
    private final LpsOrderService lpsOrderService;
    // 修改这行代码
    private final static String DESTINATION = "/queue/greeting";
    private final static String SENDER = "root";

    /**
     * 用户连接事件处理
     *
     * @param event 用户连接事件
     */
    @EventListener
    public void handleUserConnectionEvent(UserConnectionEvent event) {
        String username = event.getUsername();

        if (event.isConnected()) {
            // 用户连接成功时的处理
            onlineUserService.addOnlineUser(username);
            //log.info("User 连接成功ws: {}", username);
            // 延迟发送消息，确保连接完全建立
            CompletableFuture.runAsync(() -> {
                try {
                    // 等待连接完全建立
                    Thread.sleep(500);

                    // 查询当前连接用户的未下载数量
                    LpsOrderNODownloadVO noDownloadUser = lpsOrderService.getNoDownloadUser(username);
                    if (Objects.nonNull(noDownloadUser) && noDownloadUser.getNum() > 0) {
                        messagingTemplate.convertAndSendToUser(username, DESTINATION,new ChatMessage(SENDER, String.valueOf(noDownloadUser.getNum())));
                        //log.info("WebSocket发送订单提醒消息发送完成: 用户={}", username);
                    }
                } catch (Exception e) {
                    log.error("WebSocket发送订单提醒消息失败: 用户={}", username, e);
                }
            });
        } else {
            // 用户断开连接时的处理
            onlineUserService.removeOnlineUser(username);
            //log.info("User 关闭连接ws: {}", username);
        }

        // 推送在线用户人数
        messagingTemplate.convertAndSend("/topic/onlineUserCount", onlineUserService.getOnlineUserCount());
    }

}
